package Z.dailyExercise._0225;

public class _剑指Offer22链表中倒数第k个节点 {
    /**
     * 假设连标长度为len 倒数第k个 就是正数 len-（k-1）
     * =返回不了连标 只是结点？？
     * @param head
     * @param k
     * @return
     */
    public ListNode getKthFromEnd(ListNode head, int k) {
        if (head == null){
            return null;
        }
        ListNode res =head,temp= head;
        int count =0,len=0;
        while (head != null){
            len++;
            head = head.next;
        }
        if (k>len){
            return null;
        }
        while (count != len-(k-1) ){

            temp = temp.next;
            count++;
        }
        res = res.next;


        return res;

    }
    /**
     * 题解：不需要直到长度 两个指针 快的先走到位置k时 两个一起走 直到fast==null 也就是 倒数k位置
     */
    public ListNode getKthFromEnd1(ListNode head, int k) {
        if (head == null){
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        int n=0;
        while (n != k){
            fast = fast.next;
            n++;
        }
        while (fast != null){
            fast = fast.next;
            slow = slow.next;
        }

        return slow;
    }
}
